import React, { useState } from 'react';
import { PrismLight as SyntaxHighlighter } from 'react-syntax-highlighter';
import styled from '@emotion/styled';
import { Button, message } from 'antd';
import { CopyOutlined, CheckOutlined } from '@ant-design/icons';
import { keyframes } from '@emotion/react';

// Load specific language syntax - only import the languages we actually need to support
import typescript from 'react-syntax-highlighter/dist/esm/languages/prism/typescript';
import javascript from 'react-syntax-highlighter/dist/esm/languages/prism/javascript';
import bash from 'react-syntax-highlighter/dist/esm/languages/prism/bash';
import html from 'react-syntax-highlighter/dist/esm/languages/prism/markup';
import css from 'react-syntax-highlighter/dist/esm/languages/prism/css';

// Register languages
SyntaxHighlighter.registerLanguage('typescript', typescript);
SyntaxHighlighter.registerLanguage('javascript', javascript);
SyntaxHighlighter.registerLanguage('bash', bash);
SyntaxHighlighter.registerLanguage('html', html);
SyntaxHighlighter.registerLanguage('css', css);

interface CodeBlockProps {
  code: string;
  language?: string;
  showLineNumbers?: boolean;
}

const fadeIn = keyframes`
  from {
    opacity: 0;
    transform: translateY(-4px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
`;

// 代码内容容器
const CodeContent = styled.div`
  padding: 16px;
  background: #1e1e1e;
  
  pre {
    margin: 0 !important;
    background: transparent !important;
    padding: 0 !important;
  }
  
  code {
    font-family: "SF Mono", Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !important;
    font-size: 14px !important;
    line-height: 1.5 !important;
    text-shadow: none !important;
  }
`;

// VS Code风格的代码块容器
const CodeBlockContainer = styled.div`
  position: relative;
  overflow: hidden;
  background: #1e1e1e;
  margin: 10px 0 20px 0;
  border-radius: 6px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  font-family: 'SF Mono', Menlo, Monaco, 'Courier New', monospace;

  &:hover .code-copy-button {
    opacity: 1;
  }
`;

// 代码块头部
const CodeHeader = styled.div`
  background-color: #252526;
  padding: 8px 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 36px;
  border-bottom: 1px solid #333;
  user-select: none;
`;

// 左侧区域
const HeaderLeft = styled.div`
  display: flex;
  align-items: center;
  gap: 10px;
`;

// 窗口按钮
const TerminalButtons = styled.div`
  display: flex;
  gap: 7px;
`;

// 各个窗口按钮样式
const TerminalButton = styled.div`
  width: 12px;
  height: 12px;
  border-radius: 50%;
  position: relative;

  &:first-of-type {
    background-color: #ff5f56;
    border: 0.5px solid #e0443e;
  }

  &:nth-of-type(2) {
    background-color: #ffbd2e;
    border: 0.5px solid #dea123;
  }

  &:last-of-type {
    background-color: #27c93f;
    border: 0.5px solid #1aab29;
  }
`;

// 代码类型标题
const CodeTitle = styled.div`
  color: #999;
  font-size: 12px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
`;

// 复制按钮容器
const CopyButtonWrapper = styled.div`
  position: absolute;
  top: 6px;
  right: 10px;
  display: flex;
  align-items: center;
`;

// 复制按钮
const CopyButton = styled(Button)<{ $copied: boolean }>`
  opacity: 0;
  transition: all 0.2s ease;
  padding: 3px 8px;
  height: 24px;
  background: ${props => props.$copied ? 'rgba(39, 201, 63, 0.1)' : 'rgba(255, 255, 255, 0.05)'};
  border: 1px solid ${props => props.$copied ? 'rgba(39, 201, 63, 0.2)' : '#444'};
  border-radius: 4px;
  color: ${props => props.$copied ? '#27c93f' : 'rgba(255, 255, 255, 0.7)'};
  display: flex;
  align-items: center;
  gap: 5px;

  &:hover {
    background: ${props => props.$copied ? 'rgba(39, 201, 63, 0.15)' : 'rgba(255, 255, 255, 0.1)'} !important;
    color: ${props => props.$copied ? '#27c93f' : '#fff'} !important;
    border-color: ${props => props.$copied ? 'rgba(39, 201, 63, 0.25)' : '#555'} !important;
  }

  &.code-copy-button {
    opacity: 0;
  }

  .anticon {
    font-size: 13px;
  }

  span + span {
    margin-left: 2px;
    font-size: 11px;
  }
`;

// 命令行风格代码块容器 - 针对截图中的样式
const TerminalCodeBlockContainer = styled(CodeBlockContainer)`
  background: #0c0c0c;
  border: none;
`;

// 命令行风格头部
const TerminalHeader = styled(CodeHeader)`
  background: #202020;
  border-bottom: none;
  border-top-left-radius: 6px;
  border-top-right-radius: 6px;
`;

// 命令行风格内容
const TerminalContent = styled(CodeContent)`
  background: #0c0c0c;
  padding: 12px 16px;
  font-family: 'SF Mono', Menlo, Monaco, 'Courier New', monospace;
  color: #f0f0f0;
  
  .hljs {
    background: transparent !important;
  }
  
  .hljs-keyword, .hljs-built_in {
    color: #569CD6;
  }
  
  .hljs-string {
    color: #CE9178;
  }
  
  .hljs-comment {
    color: #6A9955;
  }
  
  pre {
    background: transparent !important;
  }
  
  code {
    white-space: pre-wrap !important;
  }
`;

// VS Code风格的代码高亮主题
const vsCodeTheme = {
  'code[class*="language-"]': {
    color: '#d4d4d4',
    textShadow: 'none',
    fontFamily: 'Menlo, Monaco, Consolas, "Andale Mono", "Ubuntu Mono", "Courier New", monospace',
    direction: 'ltr',
    textAlign: 'left',
    whiteSpace: 'pre',
    wordSpacing: 'normal',
    wordBreak: 'normal',
    lineHeight: '1.5',
    MozTabSize: '4',
    OTabSize: '4',
    tabSize: '4',
    WebkitHyphens: 'none',
    MozHyphens: 'none',
    msHyphens: 'none',
    hyphens: 'none',
  },
  'doctype': {
    color: '#808080'
  },
  'doctype.doctype-tag': {
    color: '#569CD6',
  },
  'doctype.name': {
    color: '#9CDCFE',
  },
  'comment': {
    color: '#6A9955',
  },
  'prolog': {
    color: '#6A9955',
  },
  'punctuation': {
    color: '#d4d4d4',
  },
  'property': {
    color: '#9CDCFE',
  },
  'tag': {
    color: '#569CD6',
  },
  'boolean': {
    color: '#569CD6',
  },
  'number': {
    color: '#B5CEA8',
  },
  'constant': {
    color: '#9CDCFE',
  },
  'symbol': {
    color: '#B5CEA8',
  },
  'selector': {
    color: '#D7BA7D',
  },
  'attr-name': {
    color: '#9CDCFE',
  },
  'string': {
    color: '#CE9178',
  },
  'char': {
    color: '#CE9178',
  },
  'builtin': {
    color: '#4EC9B0',
  },
  'operator': {
    color: '#d4d4d4',
  },
  'entity': {
    color: '#4EC9B0',
  },
  'url': {
    color: '#9CDCFE',
  },
  'atrule': {
    color: '#C586C0',
  },
  'attr-value': {
    color: '#CE9178',
  },
  'keyword': {
    color: '#569CD6',
  },
  'function': {
    color: '#DCDCAA',
  },
  'regex': {
    color: '#D16969',
  },
  'important': {
    color: '#569CD6',
  },
  'variable': {
    color: '#9CDCFE',
  },
  'bold': {
    fontWeight: 'bold',
  },
  'italic': {
    fontStyle: 'italic',
  }
};

const CodeBlock: React.FC<CodeBlockProps> = ({ code, language = 'typescript', showLineNumbers = false }) => {
  const [copied, setCopied] = useState(false);
  const isTerminal = language === 'bash' || language === 'shell' || language === 'sh';

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(code);
      setCopied(true);
      
      // 显示消息提示
      message.success({
        content: '代码已复制',
        duration: 2,
        style: {
          marginTop: '15vh',
        },
      });

      // 重置复制按钮状态
      setTimeout(() => {
        setCopied(false);
      }, 2000);
    } catch (err) {
      message.error({
        content: '复制失败',
        duration: 2,
        style: {
          marginTop: '15vh',
        },
      });
    }
  };

  if (isTerminal) {
    return (
      <TerminalCodeBlockContainer>
        <TerminalHeader>
          <HeaderLeft>
            <TerminalButtons>
              <TerminalButton />
              <TerminalButton />
              <TerminalButton />
            </TerminalButtons>
            <CodeTitle>{language === 'sh' ? 'shell' : language}</CodeTitle>
          </HeaderLeft>
          <CopyButtonWrapper>
            <CopyButton
              className="code-copy-button"
              icon={copied ? <CheckOutlined /> : <CopyOutlined />}
              onClick={handleCopy}
              $copied={copied}
              size="small"
            >
              {copied ? '已复制' : '复制'}
            </CopyButton>
          </CopyButtonWrapper>
        </TerminalHeader>
        <TerminalContent>
          {React.createElement(SyntaxHighlighter as any, {
            language: 'bash',
            style: vsCodeTheme,
            showLineNumbers: false,
            customStyle: {
              margin: 0,
              padding: 0,
              background: 'transparent',
            },
            children: code
          })}
        </TerminalContent>
      </TerminalCodeBlockContainer>
    );
  }

  return (
    <CodeBlockContainer>
      <CodeHeader>
        <HeaderLeft>
          <TerminalButtons>
            <TerminalButton />
            <TerminalButton />
            <TerminalButton />
          </TerminalButtons>
          <CodeTitle>{language}</CodeTitle>
        </HeaderLeft>
        <CopyButtonWrapper>
          <CopyButton
            className="code-copy-button"
            icon={copied ? <CheckOutlined /> : <CopyOutlined />}
            onClick={handleCopy}
            $copied={copied}
            size="small"
          >
            {copied ? '已复制' : '复制'}
          </CopyButton>
        </CopyButtonWrapper>
      </CodeHeader>
      <CodeContent>
        {React.createElement(SyntaxHighlighter as any, {
          language,
          style: vsCodeTheme,
          showLineNumbers,
          customStyle: {
            margin: 0,
            padding: 0,
            background: 'transparent',
          },
          children: code
        })}
      </CodeContent>
    </CodeBlockContainer>
  );
};

export default CodeBlock; 